package com.hspedu.com.jdbc.utils;

import org.junit.Test;

import java.sql.*;

/**
 * @author DL5O
 * @version 1.0
 * 该类演示如何使用JDBC工具类，完成DML和select语句
 */
public class JDBCUtils_Use {
    @Test
    public void testDML() {//insert,update,delete
        //1.得到连接
        Connection connection = null;
        //2.组织修改语句
        String sql = "update actor set name = ?  where id = ?";
        PreparedStatement preparedStatement = null;
        try {
            connection = JDBCUtils.getConnection();
            preparedStatement = connection.prepareStatement(sql);
            //给占位符赋值
            preparedStatement.setString(1,"小龙");
            preparedStatement.setInt(2,1);
            int rows = preparedStatement.executeUpdate();
            if (rows > 0) {
                System.out.println("执行成功");
            } else {
                System.out.println("执行失败");
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            //关闭资源
            JDBCUtils.close(null,preparedStatement,connection);
        }
    }

    @Test
    //测试查询语句
    public void testSelect(){
        //1.得到连接
        Connection connection = null;
        //2.组织修改语句
        String sql = "select * from actor";
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        try {
            connection = JDBCUtils.getConnection();
            preparedStatement = connection.prepareStatement(sql);
            //给占位符赋值
            resultSet = preparedStatement.executeQuery();
            while(resultSet.next()){
                int id = resultSet.getInt("id");
                String name = resultSet.getString("name");
                String sex = resultSet.getString("sex");
                Date borndate = resultSet.getDate("borndate");
                String phone = resultSet.getString("phone");
                System.out.println(id + "\t" + name + "\t"
                        + sex + "\t" + borndate + "\t" + phone);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            //关闭资源
            JDBCUtils.close(resultSet,preparedStatement,connection);
        }
    }
}
